import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { Image } from 'react-vant';
import styles from './index.module.less';
import axios from '../../api';

export default function Mine() {
  const navigate = useNavigate();
  const [nickname, setNickname] = useState('喔哩嘎');
  const [avatarUrl, setAvatarUrl] = useState('https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg');

  // 退出登录
  const handleLogout = () => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('user');
    navigate('/login');
  };

  useEffect(() => {
  // 只请求用户信息，token 由 axios 拦截器处理
  axios.get('/user/profile')
    .then(res => {
      const user = res.data || {};
      setNickname(user.nickname || '喔哩嘎');
      if (user.avatar) setAvatarUrl(user.avatar);
    })
    .catch(err => {
      console.error(err); // 只打印，不处理 token
    });
}, []);


  return (
    <div className={styles.container}>
      {/* 头像和基本信息 */}
      <div className={styles.profileCard}>
        <Image
          width={80}
          height={80}
          src={avatarUrl}
          className={styles.avatar}
        />
        <div className={styles.profileInfo}>
          <h2 className={styles.profileName}>{nickname}</h2>
          <p className={styles.profileBio}>健身爱好者 | 已坚持128天</p>
        </div>
      </div>

      {/* 我的成就 */}
      <div className={styles.achievements}>
        <h3>我的成就</h3>
        <div className={styles.achievementsList}>
          <div className={styles.achievementItem}>
            <div className={styles.statValue}>15</div>
            <div className={styles.statLabel}>连续打卡</div>
          </div>
          <div className={styles.achievementItem}>
            <div className={styles.statValue}>42</div>
            <div className={styles.statLabel}>训练完成</div>
          </div>
          <div className={styles.achievementItem}>
            <div className={styles.statValue}>8</div>
            <div className={styles.statLabel}>饮食记录</div>
          </div>
        </div>
      </div>

      {/* 功能按钮 */}
      <div className={styles.actions}>
        <button onClick={() => navigate('/ai')} className={styles.btn1}>AI助手</button>
        <button onClick={handleLogout} className={styles.btn2}>退出登录</button>
      </div>
    </div>
  );
}
